/**
 * AI问答连接封装模块
 * 提供AI对话的连接管理、消息处理、错误处理等功能
 */

import request from './request'
import { Message, Loading } from 'element-ui'

class AIConnect {
  constructor(options = {}) {
    this.baseURL = options.baseURL || '/api/ai'
    this.apiKey = options.apiKey || ''
    this.model = options.model || 'gpt-3.5-turbo'
    this.maxTokens = options.maxTokens || 2048
    this.temperature = options.temperature || 0.7
    this.timeout = options.timeout || 30000
    this.retryTimes = options.retryTimes || 3
    this.retryDelay = options.retryDelay || 1000

    // 连接状态
    this.isConnected = false
    this.isLoading = false
    this.connectionId = null

    // 消息历史
    this.messageHistory = []
    this.maxHistoryLength = options.maxHistoryLength || 50

    // 事件回调
    this.onMessage = options.onMessage || (() => { })
    this.onError = options.onError || (() => { })
    this.onConnect = options.onConnect || (() => { })
    this.onDisconnect = options.onDisconnect || (() => { })
    this.onLoading = options.onLoading || (() => { })

    // 加载实例
    this.loadingInstance = null
  }

  /**
   * 初始化AI连接
   */
  async init () {
    try {
      this.showLoading('正在初始化AI连接...')

      // 验证配置
      if (!this.validateConfig()) {
        throw new Error('AI配置验证失败')
      }

      // 建立连接
      const response = await this.establishConnection()

      if (response.success) {
        this.isConnected = true
        this.connectionId = response.connectionId
        this.onConnect(this.connectionId)
        this.hideLoading()
        return { success: true, connectionId: this.connectionId }
      } else {
        throw new Error(response.message || '连接建立失败')
      }
    } catch (error) {
      this.handleError(error)
      return { success: false, error: error.message }
    }
  }

  /**
   * 发送消息到AI
   * @param {string} message - 用户消息
   * @param {object} options - 发送选项
   */
  async sendMessage (message, options = {}) {
    if (!this.isConnected) {
      throw new Error('AI连接未建立，请先调用init()方法')
    }

    try {
      this.isLoading = true
      this.onLoading(true)
      this.showLoading('AI正在思考中...')

      // 添加用户消息到历史
      this.addMessageToHistory('user', message)

      // 构建请求参数
      const requestData = this.buildRequestData(message, options)

      // 发送请求
      const response = await this.sendRequest(requestData)

      if (response.success) {
        const aiMessage = response.data.message
        this.addMessageToHistory('assistant', aiMessage)
        this.onMessage(aiMessage, response.data)
        return { success: true, message: aiMessage, data: response.data }
      } else {
        throw new Error(response.message || 'AI响应失败')
      }
    } catch (error) {
      this.handleError(error)
      return { success: false, error: error.message }
    } finally {
      this.isLoading = false
      this.onLoading(false)
      this.hideLoading()
    }
  }

  /**
   * 流式发送消息（支持实时响应）
   * @param {string} message - 用户消息
   * @param {object} options - 发送选项
   */
  async sendMessageStream (message, options = {}) {
    if (!this.isConnected) {
      throw new Error('AI连接未建立，请先调用init()方法')
    }

    try {
      this.isLoading = true
      this.onLoading(true)
      this.showLoading('AI正在思考中...')

      // 添加用户消息到历史
      this.addMessageToHistory('user', message)

      // 构建请求参数
      const requestData = this.buildRequestData(message, { ...options, stream: true })

      // 发送流式请求
      const response = await this.sendStreamRequest(requestData)

      if (response.success) {
        const aiMessage = response.data.message
        this.addMessageToHistory('assistant', aiMessage)
        this.onMessage(aiMessage, response.data)
        return { success: true, message: aiMessage, data: response.data }
      } else {
        throw new Error(response.message || 'AI流式响应失败')
      }
    } catch (error) {
      this.handleError(error)
      return { success: false, error: error.message }
    } finally {
      this.isLoading = false
      this.onLoading(false)
      this.hideLoading()
    }
  }

  /**
   * 清除消息历史
   */
  clearHistory () {
    this.messageHistory = []
    return { success: true, message: '消息历史已清除' }
  }

  /**
   * 获取消息历史
   */
  getHistory () {
    return [...this.messageHistory]
  }

  /**
   * 断开AI连接
   */
  async disconnect () {
    try {
      if (this.connectionId) {
        await request.post(`${this.baseURL}/disconnect`, {
          connectionId: this.connectionId
        })
      }

      this.isConnected = false
      this.connectionId = null
      this.onDisconnect()

      return { success: true, message: 'AI连接已断开' }
    } catch (error) {
      this.handleError(error)
      return { success: false, error: error.message }
    }
  }

  /**
   * 重新连接
   */
  async reconnect () {
    await this.disconnect()
    return await this.init()
  }

  /**
   * 验证配置
   */
  validateConfig () {
    if (!this.apiKey) {
      console.warn('AI API Key未设置')
    }

    if (!this.baseURL) {
      console.warn('AI服务地址未设置')
      return false
    }

    return true
  }

  /**
   * 建立连接
   */
  async establishConnection () {
    const response = await request.post(`${this.baseURL}/connect`, {
      apiKey: this.apiKey,
      model: this.model,
      maxTokens: this.maxTokens,
      temperature: this.temperature
    })

    return response
  }

  /**
   * 构建请求数据
   */
  buildRequestData (message, options = {}) {
    const messages = this.messageHistory.map(msg => ({
      role: msg.role,
      content: msg.content
    }))

    // 添加当前消息
    messages.push({
      role: 'user',
      content: message
    })

    return {
      connectionId: this.connectionId,
      messages: messages,
      model: options.model || this.model,
      maxTokens: options.maxTokens || this.maxTokens,
      temperature: options.temperature || this.temperature,
      stream: options.stream || false,
      ...options
    }
  }

  /**
   * 发送请求
   */
  async sendRequest (data) {
    let retryCount = 0

    while (retryCount < this.retryTimes) {
      try {
        const response = await request.post(`${this.baseURL}/chat`, data, {
          timeout: this.timeout
        })
        return response
      } catch (error) {
        retryCount++
        if (retryCount >= this.retryTimes) {
          throw error
        }
        await this.delay(this.retryDelay * retryCount)
      }
    }
  }

  /**
   * 发送流式请求
   */
  async sendStreamRequest (data) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      let responseText = ''

      xhr.open('POST', `${this.baseURL}/chat/stream`, true)
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.timeout = this.timeout

      xhr.onreadystatechange = () => {
        if (xhr.readyState === 3) { // 接收数据中
          const newData = xhr.responseText.substring(responseText.length)
          responseText = xhr.responseText

          try {
            const lines = newData.split('\n')
            lines.forEach(line => {
              if (line.startsWith('data: ')) {
                const data = JSON.parse(line.substring(6))
                if (data.type === 'message') {
                  this.onMessage(data.content, data)
                }
              }
            })
          } catch (e) {
            // 忽略解析错误
          }
        } else if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            try {
              const response = JSON.parse(responseText)
              resolve(response)
            } catch (e) {
              reject(new Error('响应解析失败'))
            }
          } else {
            reject(new Error(`请求失败: ${xhr.status}`))
          }
        }
      }

      xhr.onerror = () => reject(new Error('网络错误'))
      xhr.ontimeout = () => reject(new Error('请求超时'))

      xhr.send(JSON.stringify(data))
    })
  }

  /**
   * 添加消息到历史
   */
  addMessageToHistory (role, content) {
    this.messageHistory.push({
      role,
      content,
      timestamp: new Date().toISOString()
    })

    // 限制历史记录长度
    if (this.messageHistory.length > this.maxHistoryLength) {
      this.messageHistory = this.messageHistory.slice(-this.maxHistoryLength)
    }
  }

  /**
   * 显示加载状态
   */
  showLoading (text = '加载中...') {
    this.loadingInstance = Loading.service({
      lock: true,
      text: text,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }

  /**
   * 隐藏加载状态
   */
  hideLoading () {
    if (this.loadingInstance) {
      this.loadingInstance.close()
      this.loadingInstance = null
    }
  }

  /**
   * 错误处理
   */
  handleError (error) {
    console.error('AI连接错误:', error)
    this.onError(error)
    Message.error(error.message || 'AI服务异常')
  }

  /**
   * 延迟函数
   */
  delay (ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  /**
   * 获取连接状态
   */
  getStatus () {
    return {
      isConnected: this.isConnected,
      isLoading: this.isLoading,
      connectionId: this.connectionId,
      historyLength: this.messageHistory.length
    }
  }

  /**
   * 设置配置
   */
  setConfig (config) {
    Object.assign(this, config)
  }

  /**
   * 获取配置
   */
  getConfig () {
    return {
      baseURL: this.baseURL,
      model: this.model,
      maxTokens: this.maxTokens,
      temperature: this.temperature,
      timeout: this.timeout,
      retryTimes: this.retryTimes,
      retryDelay: this.retryDelay,
      maxHistoryLength: this.maxHistoryLength
    }
  }
}

// 创建默认实例
const aiConnect = new AIConnect()

// 导出类和实例
export default AIConnect
export { aiConnect }

// 使用示例：
/*
import { aiConnect } from '@/utils/aiconnect'

// 初始化
await aiConnect.init()

// 发送消息
const response = await aiConnect.sendMessage('你好，请介绍一下Vue.js')

// 流式发送
await aiConnect.sendMessageStream('写一个Vue组件')

// 获取历史
const history = aiConnect.getHistory()

// 断开连接
await aiConnect.disconnect()
*/
